import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'
import Rights from '../components/power/Rights.vue'
import Roles from '../components/power/Roles.vue'
import Cate from '../components/goods/Cate'
import Params from '../components/goods/Params'
import List from '../components/goods/List'
import Add from '../components/goods/Add'
import Order from '../components/order/Order'
import Report from '../components/report/Report'
Vue.use(VueRouter)

const router = new VueRouter({
    routes: [{
                // 对初始化路径进行重定向，跳转到登录
                path: '/',
                redirect: '/login' //重定向
            }, {
                path: '/login',
                component: Login
            },
            {
                path: '/home',
                redirect: '/home/welcome',
                component: Home,
                children: [{
                    path: 'welcome',
                    component: Welcome
                }, {
                    path: 'users',
                    component: Users
                }, {
                    path: 'rights',
                    component: Rights
                }, {
                    path: 'roles',
                    component: Roles
                }, {
                    path: 'categories',
                    component: Cate
                }, {
                    path: 'params',
                    component: Params
                }, {
                    path: 'goods',
                    component: List,
                }, {
                    path: 'goods/add',
                    component: Add
                }, {
                    path: 'orders',
                    component: Order
                }, {
                    path: 'reports',
                    component: Report
                }]
            }
        ]
        // 前置全局守卫：每次路由访问前都要执行
})
router.beforeEach((to, from, next) => {
    // 对权限进行认证，目的：如果用户是通过特殊的URL跳转到非登陆页面
    // 那么我们就必须强制要求用户登录

    // 如果用户将要访问的是登录页面，那么直接放行，让其可以进入到登陆页面
    // 登陆页面没有权限限定
    if (to.path === '/login') return next()

    // 如果将要访问的不是登陆页面，则对其token进行判断，
    // 如果不存在token，则next到登陆页面
    const tokenStr = sessionStorage.getItem('token')
    if (to.path !== '/login') {
        if (tokenStr === null) { // 如果tokenStr不存在(存在：true，不存在：false)
            // 取反(不存在：true，进入if中)
            // 则强制跳转回登陆页面
            return next('/login')
        }
    }
    // 如果用户将要访问的不是登陆页面，并且有token，则允许他其他的操作
    next()
})
export default router